<?php

namespace shisou\tpgii\handler;

class ParseFile
{
    /**
     * 分析已存在文件
     * @param string $file
     *
     * @return array
     */
    public function get(string $file)
    {
        $contents = file_get_contents($file);
        $lines    = explode("\n", str_replace("\r", '', $contents));
        $cntLine  = count($lines);

        $customProperties = " * ---------- CUSTOM PROPERTIES ----------" . "\n";
        $implements       = '';
        $use              = '';

        for ($i = 0; $i < $cntLine; $i++) {
            $line = $lines[$i];

            if (strpos($line, '---------- CUSTOM PROPERTIES ----------') !== false) {
                // 自定义property
                for ($i++; $i < $cntLine; $i++) {
                    if (strpos($lines[$i], '@property') !== false) {
                        $customProperties .= $lines[$i] . "\n";
                    } else {
                        break;
                    }
                }
            } elseif (strpos($line, 'implements') !== false) {
                // implements
                $implements .= substr($line, strpos($line, 'implements'));
                break;
            } elseif (str_starts_with($line, 'use') && $line != 'use think\db\exception\DataNotFoundException;' && $line != 'use think\db\exception\DbException;' && $line != 'use think\db\exception\ModelNotFoundException;' && $line != 'use \think\Model;') {
                // use
                $use .= $line . "\n";
            }
        }

        return [
            'use'              => $use,
            'customProperties' => $customProperties,
            'implements'       => $implements,
            'customContent'    => $this->getCustom($file),
        ];
    }

    /**
     * @param string $file
     *
     * @return mixed|string
     */
    public function getCustom(string $file)
    {
        $ct    = '';
        $lines = explode("// ---------- Custom code below ----------", file_get_contents($file));

        return $lines[1];
    }
}
